const jwt = require('jsonwebtoken')

class Token {
  userId
  username
  accessToken
  secret = 'magician-ddd'
  exp = 3600 // 默认一小时，单位：秒
  sign() {
    const curTime = Math.floor(Date.now() / 1000)
    const exp = curTime + this.exp
    this.accessToken = jwt.sign(
      {
        userId: this.userId,
        username: this.username,
        exp,
        iat: curTime,
      },
      this.secret
    )
  }
  verify() {
    const { userId, username } = jwt.verify(this.accessToken, this.secret)
    this.userId = userId
    this.username = username
  }
  static createFromUser(user, options) {
    const token = new Token()
    token.username = user.username
    token.userId = user.id
    if (options) {
      token.secret = options.secret
      token.exp = options.exp
    }
    return token
  }
  static createFromToken(accessToken, options) {
    const token = new Token()
    token.accessToken = accessToken
    if (options) {
      token.secret = options.secret
      token.exp = options.exp
    }
    return token
  }
}

module.exports = Token
